package com.liam.apppush.client.huawei;

import com.alibaba.fastjson.JSONObject;
import com.liam.apppush.config.HuaWeiConfig;
import com.liam.apppush.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 华为推送
 * 1 可以批量推送，每次不能超过1000  /或按主题单个发送
 * 2 可以订/退 主题 每次设置1000个用户
 *
 * 3 暂时没看到全推
 */
@Slf4j
@Component
public class HaiweiClient extends HuaWeiConfig {

    public static final String ACCESS_TOKEN_URL = "https://oauth-login.cloud.huawei.com/oauth2/v3/token";
    public static String PUSH_URL = "https://push-api.cloud.huawei.com/v1/%s/messages:send";
    public static String SUBSCRIBE_URL = "https://push-api.cloud.huawei.com/v1/%s/topic:subscribe";
    public static String UNSUBSCRIBE_URL = "https://push-api.cloud.huawei.com/v1/[appid]/topic:unsubscribe";



    /**
     * 获取 access token
     * @return
     * @throws IOException
     */
    public String getAccessToken() throws IOException {
        Map<String,String> map = new HashMap<>();
        map.put("grant_type","client_credentials");
        map.put("client_id",oAuthClientId);
        map.put("client_secret",oAuthClientSecret);

        JSONObject result = HttpUtil.httpPostMap(ACCESS_TOKEN_URL,map);
        if(result != null){
            log.info("getAccessToken : {}",result.toJSONString());
            return result.getString("access_token");
        }
        return null;
    }

    /**
     *
     * tokens  数量不能超过   1000
     * 发送消息
     * @return
     */
    public JSONObject sendPushMessage(String title,String content,List<String> tokens) throws IOException {
        String url = String.format(PUSH_URL,appId);

        Map<String,String> headers = new HashMap<>();
        headers.put("Authorization","Bearer CgB6e3x9JcwnIFZ9HhQbTBevUQHcK+LBf5hwzCqmgXEhQxQy2ldlIQSe4t2KKTYfSBkYJrgmnavtZKdePFHshfIm1");
        headers.put("Content-Type", "application/json");

        JSONObject param = buildParam(title,content,tokens);

        JSONObject result = HttpUtil.httpPost(url,headers,param);
        log.info("sendPushMessage : {}" ,result.toJSONString());

        return null;
    }


    /**
     * * {
     *    "validate_only": false,
     *    "message": {
     *        "notification": {
     *            "title": "title",
     *            "body": "body"
     *        },
     *        "android": {
     *            "notification": {
     *                "title": "android title",
     *                "body": "android body",
     *                "click_action": {
     *                    "type": 1,
     *                    "intent": "#Intent;compo=com.rvr/.Activity;S.W=U;end"
     *                }
     *            }
     *        },
     *        "token": [
     *            "pushtoken1",
     *            "pushtoken2"
     *        ]
     *    }
     *}
     * @param tokens
     * @return
     */
    private JSONObject buildParam(String title,String content,List<String> tokens) {
        JSONObject param = new JSONObject();
        JSONObject message = new JSONObject();

        param.put("validate_only",false);//true：测试消息 false：正式消息
        param.put("message",message);

        JSONObject notification = new JSONObject();
        JSONObject android = new JSONObject();
        message.put("notification",notification);
        message.put("android",android);

        // token/topic/condition三者只能且必须设置一个。
        message.put("token",tokens.toArray());
//        message.put("topic","");

        notification.put("title",title);
        notification.put("body",title);

//        notification.put("image","http://"); 用户自定义的通知栏消息右侧大图标URL，如果不设置，则不展示通知栏右侧图标。URL使用的协议必须是HTTPS协议，图标文件须小于512KB，图标建议规格大小：40dp x 40dp，弧角大小为8dp，超出建议规格大小的图标会存在图片压缩或显示不全的情况。

        return param;
    }


    /**
     * 订阅
     * @param topic
     * @param tokens
     * @return
     * @throws IOException
     */
    public JSONObject subscribe(String topic ,List<String> tokens) throws IOException {
        String url = String.format(SUBSCRIBE_URL,appId);

        Map<String,String> headers = new HashMap<>();
        headers.put("Authorization","Bearer CgB6e3x9JcwnIFZ9HhQbTBevUQHcK+LBf5hwzCqmgXEhQxQy2ldlIQSe4t2KKTYfSBkYJrgmnavtZKdePFHshfIm1");
        headers.put("Content-Type", "application/json");

        JSONObject param = new JSONObject();
        param.put("topic",topic);

        JSONObject result = HttpUtil.httpPost(url,headers,param);
        log.info("subscribe : {}" ,result.toJSONString());
        return null;
    }

    /**
     * 退订
     * @param topic
     * @param tokens
     * @return
     * @throws IOException
     */
    public JSONObject unSubscribe(String topic ,List<String> tokens) throws IOException {
        String url = String.format(SUBSCRIBE_URL,appId);

        Map<String,String> headers = new HashMap<>();
        headers.put("Authorization","Bearer CgB6e3x9JcwnIFZ9HhQbTBevUQHcK+LBf5hwzCqmgXEhQxQy2ldlIQSe4t2KKTYfSBkYJrgmnavtZKdePFHshfIm1");
        headers.put("Content-Type", "application/json");

        JSONObject param = new JSONObject();
        param.put("topic",topic);

        JSONObject result = HttpUtil.httpPost(url,headers,param);
        log.info("unSubscribe : {}" ,result.toJSONString());
        return null;
    }


}
